<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class SignController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /** 登录 */
    public function login(Request $request)
    {
        if($request->isMethod('post')){
            $data = $request->all();

            //验证
            $validator = $this->validateLogin($data);
            if ($validator->fails()) {
                return $this->fail($validator->errors()->first());
            }

            if(Auth::guard('admin')->attempt(['username'=>$data['username'],'password'=>$data['password']])){
                return $this->success('登录成功!');
            }else{
                return $this->fail('登录验证失败!');
            }
            return response()->json($result);
        }
        /** 已存在登录的直接进入后台,不展示登录页 */
        if(Auth::guard('admin')->check()){  return redirect('/');}
        return view('user.sign.login');
    }

    /** 退出登录 */
    public function logout(Request $request)
    {
        Auth::guard('admin')->logout();
        return redirect('/login');
    }

    /** 登录验证 */
    protected function validateLogin($data){
        $validator = Validator::make($data, [
            'username'  => 'required',
            'password'  => 'required',
            'captcha'   => 'required|captcha',
        ], [
            'required'  => ':attribute不得为空',
            'captcha'   => ':attribute不正确'
        ], [
            'username'  => '用户名',
            'password'  => '密码',
            'captcha'   => '验证码',
        ]);
        return $validator;
    }

}
